<?php
/**TinyMce WYSIWYG
 * Plugin Name: tiny_mce_before_init
 * Plugin URI:  http://tinymce.ax-z.cn/
 * Description: 启用经典编辑器，并增强。
 * Version:     1.0
 * Author:      WordPress Contributors
 * Author URI:  http://tinymce.ax-z.cn/
 * License:     GPLv2 or later
 * License URI: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Text Domain: classic-widgets
 * Domain Path: /languages
 * Requires at least: 4.9
 * Requires PHP: 5.6 or later
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License version 2, as published by the Free Software Foundation. You may NOT assume
 * that you can use any other version of the GPL.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * add_filter()
 * mce_css添加样式表
 * mce_external_languages添加翻译
 * teeny_mce_buttons
 * mce_buttons
 * mce_buttons_2
 * mce_buttons_3
 * mce_buttons_4
 * tiny_mce_plugins添加插件
 * mce_external_plugins
 * quicktags_settings
 * tiny_mce_before_init
 * wp_editor_settings//'disable_for_editor'
 * 
 * 
 * wp_tiny_mce_init
 * add_options_page
 * 
 * <?php plugins_url( 'vendor/highlight.js', __FILE__ ); ?>
	<link rel="stylesheet" href="<?php echo plugins_url( 'vendor/highlight', __FILE__ ); ?>/styles/default.css">
	<script src="<?php echo plugins_url( 'vendor/highlight', __FILE__ ); ?>/highlight.js"></script>
	<script>hljs.highlightAll();</script>
 */
/**
简述
This is tinymce plugins
该项目主要为 tinymce 富文本编译器的扩展插件，或增强优化插件
目前整理完成插件列表如下：

 imagetools [增强优化]： 图片编辑工具插件， 对图片进行处理。优化跨域，功能更丰富；
 table [增强优化]：表格插件，处理表格。 增强优化表格控制，增加表格转图片功能，便捷布局按钮；
 indent2em[增强优化]：首行缩进插件。提供中文段落排版的首行缩进2个字符的功能。增强优化 加入字间距非默认情况，也能实现准确首行缩进2字符；
 letterspacing：设置间距插件。可以设置文档中的文字间距；
 layout： 一键布局插件。可以给文档段落进行一键快速排版布局；
 importword： 导入word插件。可以直接导入word ,并且保证word中图片不会丢失，自动转为base64;
 upfile： 文件上传。可以点击导入文件，可自定义编辑文件名;
 bdmap： 百度地图。 支持更改尺寸，自定义标签，开启导航功能,支持vue;
 axupimgs: 多图上传。可同时上传多组图片，支持vue;
 attachment: 附件上传。拥有附件类型对应图标，支持vue;
 */
//禁用新版编辑器
add_filter('use_block_editor_for_post', '__return_false');
add_filter( 'use_block_editor_for_post_type', '__return_false', 1000 );
remove_action( 'wp_enqueue_scripts', 'wp_common_block_scripts_and_styles' );

add_action('wp_print_scripts', 'disable_autosave');
function disable_autosave() {
    wp_deregister_script('autosave');
}
add_filter('wp_revisions_to_keep', 'specs_wp_revisions_to_keep', 10, 2);
function specs_wp_revisions_to_keep($num, $post) {
    return 0;
}

////////////将自定义样式选项添加到现有 Style 下拉列表中
function mce_buttons_1( $buttons ) {
	$toolbar1 = array(
		'formatselect',
		'bold',
		'italic',
		'bullist',
		'numlist',
		'blockquote',
		'alignleft',
		'aligncenter',
		'alignright',
		'link',
		'unlink',
		'wp_more',
		'spellchecker',
		'wp_add_media',
		'wp_adv',
	);


	$buttons_1 = array(
		// Core
		'bold' => 'Bold',
		'italic' => 'Italic',
		'underline' => 'Underline',
		'strikethrough' => 'Strikethrough',
		'alignleft' => 'Align left',
		'aligncenter' => 'Align center',
		'alignright' => 'Align right',
		'alignjustify' => 'Justify',
		'styleselect' => 'Formats',
		'formatselect' => 'Paragraph',
		'fontselect' => 'Font Family',
		'fontsizeselect' => 'Font Sizes',
		'cut' => 'Cut',
		'copy' => 'Copy',
		'paste' => 'Paste',
		'bullist' => 'Bulleted list',
		'numlist' => 'Numbered list',
		'outdent' => 'Decrease indent',
		'indent' => 'Increase indent',
		'blockquote' => 'Blockquote',
		'undo' => 'Undo',
		'redo' => 'Redo',
		'removeformat' => 'Clear formatting',
		'subscript' => 'Subscript',
		'superscript' => 'Superscript',

		// From plugins
		'hr' => 'Horizontal line',
		'link' => 'Insert/edit link',
		'unlink' => 'Remove link',
		'image' => 'Insert/edit image',
		'charmap' => 'Special character',
		'pastetext' => 'Paste as text',
		'print' => 'Print',
		'anchor' => 'Anchor',
		'searchreplace' => 'Find and replace',
		'visualblocks' => 'Show blocks',
		'visualchars' => 'Show invisible characters',
		'code' => 'Source code',
		'wp_code' => 'Code',
		'fullscreen' => 'Fullscreen',
		'insertdatetime' => 'Insert date/time',
		'media' => 'Insert/edit video',
		'nonbreaking' => 'Nonbreaking space',
		'table' => 'Table',
		'ltr' => 'Left to right',
		'rtl' => 'Right to left',
		'emoticons' => 'Emoticons',
		'forecolor' => 'Text color',
		'backcolor' => 'Background color',

		// WP
		'wp_adv'		=> 'Toolbar Toggle',
		'wp_help'		=> 'Keyboard Shortcuts',
		'wp_more'		=> 'Read more...',
		'wp_page'		=> 'Page break',

		'tadv_mark'     => 'Mark',
	);
	$pos = array_search('wp_more', $buttons, true);
    if ($pos !== false) {
        $tmp_buttons = array_slice($buttons, 0, $pos + 1);
        $tmp_buttons[] = 'formatselect';
        $tmp_buttons[] = 'fontselect';
        $tmp_buttons[] = 'fontsizeselect';
        $tmp_buttons[] = 'styleselect';
        $tmp_buttons[] = 'removeformat';
        $tmp_buttons[] = 'visualchars';
        $tmp_buttons[] = 'pastetext';
        $tmp_buttons[] = 'wp_page';
        $buttons = array_merge($tmp_buttons, array_slice($buttons, $pos + 1));
    }
    array_push( $buttons, "button_eek", "button_green" );
	return $buttons;
}
//增强编辑器开始
function mce_buttons_2($buttons) {
    $toolbar2 = array(
		'strikethrough',
		'hr',
		'forecolor',
		'pastetext',
		'removeformat',
		'charmap',
		'outdent',
		'indent',
		'undo',
		'redo',
		'wp_help',
	);

    $buttons[] = 'bold';
    $buttons[] = 'italic';
    $buttons[] = 'underline';
    $buttons[] = 'strikethrough';
    $buttons[] = 'blockquote';
    $buttons[] = 'alignleft';
    $buttons[] = 'aligncenter';
    $buttons[] = 'alignright';
    $buttons[] = 'alignjustify';
    $buttons[] = 'outdent';
    $buttons[] = 'indent';
    $buttons[] = 'forecolor';
    $buttons[] = 'backcolor';
    $buttons[] = 'bullist';
    $buttons[] = 'numlist';
    $buttons[] = 'searchreplace';
    return $buttons;
}
add_filter('mce_buttons_2', 'mce_buttons_2');


//增强编辑器开始
function mce_buttons_3($buttons) {
    $buttons[] = 'link';
    $buttons[] = 'unlink';
    $buttons[] = 'anchor';
    $buttons[] = 'hr';
    $buttons[] = 'table';
    $buttons[] = 'wp_page';
    $buttons[] = 'wp_more';
    $buttons[] = 'bootstrap';
    $buttons[] = 'template';
    $buttons[] = 'fontawesome';
    $buttons[] = 'codesample';
    $buttons[] = 'toc';
    $buttons[] = 'emoticons';
    $buttons[] = 'charmap';
    $buttons[] = 'media';
    $buttons[] = 'wp_help';
    $buttons[] = 'visualblocks';
    return $buttons;
}
add_filter('mce_buttons_3', 'mce_buttons_3');

function mce_buttons_4($buttons) {
    $buttons[] = 'newdocument';
    $buttons[] = 'cut';
    $buttons[] = 'copy';
    $buttons[] = 'paste';
    $buttons[] = 'undo';
    $buttons[] = 'redo';
    $buttons[] = 'visualaid';
    $buttons[] = 'code';
    $buttons[] = 'fullscreen';
    $buttons[] = 'help';
    array_push($buttons, "separator", "clang,langattribs");
    array_push($buttons, 'smiley');
    // $buttons[] = 'separator';
    // $buttons[] = 'clang';
    // $buttons[] = 'langattribs';
    $buttons[] = 'custombutton';
    
    return $buttons;
}
add_filter('mce_buttons_4', 'mce_buttons_4');

function prefix_custom_teeny_mce_buttons( $buttons, $editor_id ) {
    
    $buttons = array( 'formatselect', 'bold', 'italic' );
    return $buttons;

}

/**添加自定义媒体按钮 */

//输出WordPress表情
function fa_get_wpsmiliestrans() {
    global $wpsmiliestrans;
    $wpsmilies = array_unique($wpsmiliestrans);
    $output = '';
    foreach ($wpsmilies as $alt => $src_path) {
        $output.= '<a class="add-smily" data-smilies="' . $alt . '"><img class="wp-smiley" style="height:24px;width:24px;" src="' . WPMU_PLUGIN_URL . '/assets/smilies/' . rtrim($src_path, "gif") . 'gif" /></a>';
    }
    return $output;
}
function fa_smilies_custom_button($context) {
    printf( '<a href="%s" class="button my-button my-custom-button" id="my-custom-button">' . '<span class="wp-media-buttons-icon dashicons dashicons-art"></span> %s' . '</a>', '#', __( '添加表情', 'textdomain' ) );
    $context = '';
    $context.= '<style>.smilies-wrap{background:#fff;border: 1px solid #ccc;box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.24);padding: 10px;position: absolute;top: 60px;width: 375px;display:none}.smilies-wrap img{height:24px;width:24px;cursor:pointer;margin-bottom:5px} .is-active.smilies-wrap{display:block}</style> <a id="insert-media-button" style="position:relative" class="button insert-smilies add_smilies" title="添加表情" data-editor="content" href="javascript:;">^_^ 添加表情</a><div class="smilies-wrap">' . fa_get_wpsmiliestrans() . '</div><script>jQuery(document).ready(function(){jQuery(document).on("click", ".insert-smilies",function() { if(jQuery(".smilies-wrap").hasClass("is-active")){jQuery(".smilies-wrap").removeClass("is-active");}else{jQuery(".smilies-wrap").addClass("is-active");}});jQuery(document).on("click", ".add-smily",function() { send_to_editor(" " + jQuery(this).data("smilies") + " ");jQuery(".smilies-wrap").removeClass("is-active");return false;});});</script>';
    return $context;
}
add_action('media_buttons', 'fa_smilies_custom_button');
/**添加自定义媒体按钮 */

add_filter( 'mce_buttons', 'mce_buttons_1', 999, 2 );
// add_filter( 'mce_buttons_2', 'mce_buttons_2', 999, 2 );
// add_filter( 'mce_buttons_3', 'mce_buttons_3', 999, 2 );
// add_filter( 'mce_buttons_4', 'mce_buttons_4', 999, 2 );
add_filter( 'teeny_mce_buttons', 'prefix_custom_teeny_mce_buttons', 10, 2 );
// add_filter( 'tiny_mce_before_init','mce_options', 10, 2 );
// add_filter( 'mce_external_plugins', 'mce_external_plugins', 999 );
// add_filter( 'tiny_mce_plugins', 'tiny_mce_plugins', 999 );





function enqueue_scripts( $page ) {
	$plugin_url = WPMU_PLUGIN_URL . '/assets';
	$plugin_dir = WPMU_PLUGIN_DIR . '/inc';
	wp_enqueue_style( 'tadv-css', $plugin_url . '/tadv.css', array( 'editor-buttons' ), '' );
	wp_enqueue_script( 'tadv-js', $plugin_url . '/tadv.js', array( 'jquery-ui-sortable' ), '', true );
	wp_enqueue_style( 'tadv-mce-skin', includes_url( 'js/tinymce/skins/lightgray/skin.min.css' ), array(), '' );
}
//add_action( 'admin_enqueue_scripts', 'enqueue_scripts' );

function add_tiny_mce_plugins( $plugin_array ) {

	$tinymce_plugins = array(//18
		'charmap',
		'colorpicker',
		'hr',
		'lists',
		'media',
		'paste',
		'tabfocus',
		'textcolor',
		'fullscreen',
		'wordpress',
		'wpautoresize',
		'wpeditimage',
		'wpemoji',
		'wpgallery',
		'wplink',
		'wpdialogs',
		'wptextpattern',
		'wpview',
	);

	$plugins = array(//22
		'wpview',
		'charmap',
		'colorpicker',
		'compat3x',
		'directionality',
		'fullscreen',
		'hr',
		'image',//
		'link',//
		'lists',
		'media',
		'paste',
		'tabfocus',
		'textcolor',
		'wordpress',
		'wpautoresize',
		'wpdialogs',
		'wpeditimage',
		'wpemoji',
		'wpgallery',
		'wplink',
		'wptextpattern',
	);
	foreach ( $plugins as $plugin ) {
		$plugin_array[ $plugin ] = plugins_url( 'assets/tinymce/plugins/' . $plugin . '/plugin.min.js', __FILE__ );
	}

	return $plugin_array;
}
add_filter( 'tiny_mce_plugins', 'add_tiny_mce_plugins' );
/**
 * Add the TinyMCE VisualBlocks Plugin.
 *
 * @param array $plugins An array of all plugins.
 * @return array
 */
function add_mce_external_plugins( $plugin_array ) {
	$wp_plugins = array(//22
		'wpview',
		'charmap',
		'colorpicker',
		'compat3x',
		'directionality',
		'fullscreen',
		'hr',
		'image',
		'link',
		'lists',
		'media',
		'paste',
		'tabfocus',
		'textcolor',
		'wordpress',
		'wpautoresize',
		'wpdialogs',
		'wpeditimage',
		'wpemoji',
		'wpgallery',
		'wplink',
		'wptextpattern',
	);
	$best_editor_plugins = array(//23
		'print',
		'searchreplace',
		'table',
		'template',
		'toc',
		'visualblocks',
		'visualchars',
		'advlist',
		'anchor',
		'autolink',
		'autoresize',
		'autosave',
		'bootstrap',
		'code',
		'codesample',
		'contextmenu',
		'emoticons',
		'fontawesome',
		'importcss',
		'insertdatetime',
		'nonbreaking',
		'noneditable',
	);

	$tinymce_advanced_plugins = array(//15
		'emoticons',
		'importcss',
		'insertdatetime',
		'link',
		'nonbreaking',
		'print',
		'searchreplace',
		'table',
		'visualblocks',
		'visualchars',
		'wptadv',
		'advlist',
		'anchor',
		'code',
		'contextmenu',
	);

	$required_menubar_plugins = array(
		'anchor',
		'code',
		'insertdatetime',
		'nonbreaking',
		'print',
		'searchreplace',
		'table',
		'visualblocks',
		'visualchars'
	);


	$plugins = array(
		'advlist',//高级列表///best-editor
		'anchor',//锚点插件///best-editor
		'autolink',//自动链接 ///best-editor
		'autoresize',//编辑器自适应 ///best-editor
		'autosave',// 自动存稿
		//'bbcode',//没有
		'bootstrap',// ///best-editor min
		'charmap',// 特殊字符
		'code',/////best-editor
		'codesample',// ///best-editor
		'contextmenu',// ///best-editor
		//'directionality',// 文字方向 默认
		'emoticons',//表情插件 ///best-editor
		'fontawesome',/// //best-editor
		// 'fullpage',// 文档属性 没有
		'fullscreen',// 全屏
		//'help',// 帮助 没有
		'hr',// 水平分割线
		//'image',// 插入编辑图片 默认
		// 'imagetools',// 图片编辑工具
		'importcss',// 引入css ///best-editor
		'insertdatetime',// 插入日期时间 ///best-editor
		//'legacyoutput',// 输出HTML4
		//'link',// 超链接 tinymce-advanced.5.9.2
		'lists',// 列表插件
		'media',// 插入编辑媒体
		'nonbreaking',// 插入不间断空格 
		'noneditable',// 不可编辑元素 ///best-editor
		//'pagebreak',// 插入分页符
		'paste',// 粘贴插件
		'preview',// 预览 ///best-editor
		'print',// 打印 ///best-editor
		//'quickbars',// 快速工具栏
		//'save',// 保存
		'searchreplace',//查找替换 ///best-editor
		//'spellchecker',// 拼写检查
		'tabfocus',// tab切入切出
		'table',//表格插件 ///best-editor
		'template',// 内容模板 ///best-editor
		'textcolor', //文字颜色
		//'textpattern', //快速排版
		'toc',//目录生成器 ///best-editor
		'visualblocks',//显示元素范围 ///best-editor
		'visualchars', //显示不可见字符 ///best-editor
		//'wordcount', //字数统计
		'wptadv',//tinymce-advanced.5.9.2
		//'code kityformula-editor',// 数学公式

		'changelang',//mce-accessible-language-change
		'smiley',//tinymce-smiley-button

		'custombutton',

		//'my_buttons',
		// 插入百度地图
		// 首行缩进
		// 设置行高
		// 图片批量上传
		// 字数限制
		// 更多插件...

	);
	foreach ( $plugins as $plugin ) {
		$plugin_array[ $plugin ] = plugins_url( 'assets/tinymce/plugins/' . $plugin . '/plugin.min.js', __FILE__ );
	}

	return $plugin_array;
}
add_filter( 'mce_external_plugins', 'add_mce_external_plugins' );

function add_teeny_mce_plugins( $teeny_mce_plugins ) {

	$teeny_mce_plugins = array(
		'colorpicker',
		'lists',
		'fullscreen',
		'image',
		'wordpress',
		'wpeditimage',
		'wplink',
	);
	return $teeny_mce_plugins;
}
add_filter( 'teeny_mce_plugins', 'add_teeny_mce_plugins' );

function mytheme_tinymce_settings( $init , $editor_id = '' ) {

/*
		auto_focus: true,//自动获得焦点//该参数用于让编辑器加载完成后自动获得光标焦点，值为true时为当前实例，为string时是指定其他编辑的实例ID。
		base_url: '/my/tinymce/dir'//设置主程序结构所在url）
		// 5.0.8新增。
		// 如果你的tinymce.js和其它应该放到与它同级的文件夹（比如插件皮肤等）因为某种原因没有放在一起。比如tinymce.js你是用cdn引入的，但皮肤和插件你想放在项目里之类的场景，那么用此参数可以解决你的问题。
		cache_suffix: '?v=5.0.0',//cache_suffix（缓存请求后缀）
//该参数可在TinyMCE加载js和css文件时，在URL请求后面自动加上指定的后缀，多用于解决缓存问题。
		suffix（后缀）
5.0.8新增。

详细解释一下这东西，tinymce加载插件的方式很特别，如果主程序叫tinymce.js，它在加载插件时就会去找插件文件夹里的plugin.js；如果主程序叫tinymce.min.js，它在加载插件时就会去找plugin.min.js。看到这里不知道你懂没懂，这个参数简单说就是用来设置“.min”这个部分的。

取值：String
		content_security_policy: "default-src 'self'",//仅允许当前域名，不包括子域名
		content_security_policy（内容安全策略）
为编辑器的iframe内容设置自定义内容安全策略。了解详情可自行搜索：HTML5内容安全策略（CSP）。
external_plugins: {
        'testing': 'http://www.testing.com/plugin.min.js',
        'maths': 'http://www.maths.com/plugin.min.js'
    }
    external_plugins（引入站外插件）
可用于引入本站外部提供的插件，TinyMCE将根据插件加载规则加载指定URL的插件。当从CDN加载TinyMCE或希望TinyMCE主目录与自定义插件分开时，可使用此配置。

其值因为一个对象，形如{插件名:插件URL}
hidden_input（开关内联模式用于存内容的‘隐藏input’）
默认tinymce在开启内联模式（inline）会生成一个‘隐藏的input’用于执行保存动作时存放编辑器的内容。此选项默认开启，如果不需要生成这个input，可以设为false禁用此功能。
init_instance_callback（初始化结束后执行）
此配置选项允许你在编辑器初始化完成后，执行自己的回调函数。此函数支持一个参数，该参数为编辑器实例对象的引用。
setup（初始化前执行）
与init_instance_callback类似，不过这个是在开始前执行一个自定义函数。
plugins（指定需加载的插件）
为TinyMCE指定要加载的插件，此插件必须已存在plugins目录内，多个插件用空格分隔。默认TinyMCE不会加载任何插件。
readonly（只读模式）
将编辑器设置成只读模式，不可编辑。
target（使用Node替代selector）
当不方便使用css选择器指定编辑器容器的时候，例如容器需要动态创建，这种情况，可以通过直接赋予其Node对象来创建编辑器。

注意：selector优先级要高于target，如要使用target，则参数中不要出现selector。

*/
		$init['theme'] = 'modern';//inlite
		$init['skin'] = 'lightgray';//wordpress
		$init['language'] = 'zh';//wp-langs-en.js
		//$init['formats'] = '';
		$init['relative_urls'] = false;
		$init['remove_script_host'] = false;
		$init['convert_urls'] = false;
		$init['contextmenu'] = 'copy cut paste selectall link media';
		$init['browser_spellcheck'] = true;
		$init['fix_list_elements'] = true;
		// $init['font_formats']       = 'Lato=Lato;Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats';
		$init['entities'] = '38,amp,60,lt,62,gt';
		$init['entity_encoding'] = 'raw';
		//$init['extended_valid_elements'] .= ',i[style|id|name|class|lang],span[style|id|name|class|lang]';
		$init['keep_styles'] = false;
		$init['cache_suffix'] = 'wp-mce-49110-20201110';
		$init['resize'] = 'vertical';
		$init['menubar'] = true;//'file edit insert view format table tools help'
		// menu: {
	    //     file: {title: '文件', items: 'newdocument'},
	    //     edit: {title: '编辑', items: 'undo redo | cut copy paste pastetext | selectall'},
	    //     insert: {title: '插入', items: 'link media | template hr'},
	    //     view: {title: '查看', items: 'visualaid'},
	    //     format: {title: '格式', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat'},
	    //     table: {title: '表格', items: 'inserttable tableprops deletetable | cell row column'},
	    //     tools: {title: '工具', items: 'spellchecker code'}
	    // }
		$init['branding'] = '';
		$init['preview_styles'] = '';
		$init['paste_data_images']    = true;
		$init['end_container_on_empty_block'] = '';
		$init['wpeditimage_html5_captions'] = '';
		$init['wp_lang_attr'] = '';
		$init['wp_shortcut_labels'] = '';
		$init['content_css'] = '';
		
		$init['selector'] = '#content';
		$init['wpautop'] = false;
		$init['indent'] = true;
		$init['importcss_append'] = true;
		$init['templates']        = "[
			{title: 'Alert Success', description: 'Insert a success alert message box', url: '" . plugins_url( 'assets/tinymce-plugins/template/templates/alert-success.html', __FILE__ ) . "'},
			{title: 'Alert Info', description: 'Insert an info alert message box', url: '" . plugins_url( 'assets/tinymce-plugins/template/templates/alert-info.html', __FILE__ ) . "'},
			{title: 'Alert Warning', description: 'Insert a warning alert message box', url: '" . plugins_url( 'assets/tinymce-plugins/template/templates/alert-warning.html', __FILE__ ) . "'},
			{title: 'Alert Danger', description: 'Insert a danger alert message box', url: '" . plugins_url( 'assets/tinymce-plugins/template/templates/alert-danger.html', __FILE__ ) . "'},
		]";
		// $init['toolbar1'] = 'formatselect,bold,italic,blockquote,bullist,numlist,alignleft,aligncenter,alignright,link,unlink,undo,redo';//Advanced Editor Tools
		// $init['toolbar2'] = 'fontselect,fontsizeselect,outdent,indent,pastetext,removeformat,charmap,wp_more,forecolor,table,wp_help';//Advanced Editor Tools
		// $init['toolbar3'] = '';
		// $init['toolbar4'] = '';
		$init['tabfocus_elements'] = ':prev,:next';
		$init['body_class'] = 'content locale-zh-cn';
		$init['image_advtab'] = true;
		$init['rel_list'] = '[{text: "None", value: ""}, {text: "Nofollow", value: "nofollow noreferrer"}]';//Advanced Editor Tools
		$init['removed_menuitems'] = 'newdocument';
		$init['tadv_noautop'] = true;
		$init['options'] = 'classic_paragraph_block,table_resize_bars,table_grid,table_tab_navigation,table_advtab';
		$init['options'] = 'menubar,advlist,menubar_block,merge_toolbars';//Advanced Editor Tools
		//'options' => 'classic_paragraph_block,table_resize_bars,table_grid,table_tab_navigation,table_advtab',//default_admin_settings
		$init['plugins'] = 'wpview,charmap,colorpicker,compat3x,directionality,fullscreen,hr,image,link,lists,media,paste,tabfocus,textcolor,wordpress,wpautoresize,wpdialogs,wpeditimage,wpemoji,wpgallery,wplink,wptextpattern,';
		//$init['plugins'] = 'anchor,code,insertdatetime,nonbreaking,print,searchreplace,table,visualblocks,visualchars,advlist,wptadv';//Advanced Editor Tools
		// $init['external_plugins'] = "[
		// {
	    //     'testing': 'http://www.testing.com/plugin.min.js',
	    //     'maths': 'http://www.maths.com/plugin.min.js'
	    // }
	    // ]";
		$init['toolbar_classic_block'] = 'formatselect,bold,italic,blockquote,bullist,numlist,alignleft,aligncenter,alignright,' .
				'link,forecolor,backcolor,table,wp_help';
		$init['wordpress_adv_hidden'] = false;// Disable advanced row
		$init['importcss_file_filter'] = 'editor-style.css';
		$init['font_formats'] = '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif';
		$init['fontsize_formats'] = '8px 10px 12px 14px 16px 20px 24px 28px 32px 36px 48px 60px 72px 96px';
		$init['table_toolbar'] = false;
		$init['table_responsive_width'] = true;
		$init['table_resize_bars'] = false;
		$init['object_resizing'] = 'img';
		$init['table_default_attributes'] = '{}';
		$init['table_grid'] = false;
		$init['table_tab_navigation'] = false;
		$init['table_advtab'] = false;
		$init['table_cell_advtab'] = false;
		$init['table_row_advtab'] = false;
		$init['table_appearance_options'] = false;
		$init['verify_html']      = false;
		$init['noneditable_noneditable_class'] = 'fa';


		$classes = array(
			__('Test style 1', 'mytheme') => 'teststyle1',
			__('Test style 2', 'mytheme') => 'teststyle2',
			__('Test style 3', 'mytheme') => 'teststyle3',
		);

		//Delimit styles by semicolon in format 'Title=classes;' so TinyMCE can use it
		if ( ! empty( $init['theme_advanced_styles'] ) ) {
			$init['theme_advanced_styles'] .= ';';
		} else {
			//If there's nothing defined yet, define it
			$init['theme_advanced_styles'] = '';
		}

		//Loop through our newly defined classes and add them to TinyMCE
		$class_settings = '';
		foreach ( $classes as $name => $value ) {
			$class_settings .= "{$name}={$value};";
		}

		//Add our new class settings to the TinyMCE $settings array
		$init['theme_advanced_styles'] .= trim( $class_settings, '; ' );


		/*
		// Add new styles to the TinyMCE "formats" menu dropdown
		// Create array of new styles
		$new_styles = array(
			array(
				'title'	=> __( 'Custom Styles', 'wpex' ),
				'items'	=> [
					array(
						'title'	   => __('Theme Button','wpex'),
						'selector' => 'a',
						'classes'  => 'theme-button'
					),
					array(
						'title'   => __('Highlight','wpex'),
						'inline'  => 'span',
						'classes' => 'text-highlight',
					),
				),
			),
		);
		*/
		// Merge old & new styles
		$init['style_formats_merge'] = true;
		// Add new styles
		//$init['style_formats'] = json_encode( $new_styles );
		
		
		return $init;
	

}
add_filter( 'tiny_mce_before_init', 'mytheme_tinymce_settings' );
//add_filter( 'teeny_mce_before_init', 'mytheme_tinymce_settings' );

// Custom CSS
if ( ! function_exists('plugin_mce_css') ) {
    function plugin_mce_css( $mce_css ) {
        if ( ! empty( $mce_css ) )
            $mce_css .= ',';

        $mce_css .= plugins_url( '/css/changelang.css', __FILE__ );

        return $mce_css;
    }
}

add_filter( 'mce_css', 'plugin_mce_css' );

add_filter('wp_tiny_mce_popups', 'add_dropdowns');
function add_dropdowns($popups) {
    $popups['mydropdown'] = array( // 注册新的下拉菜单和弹出式窗口名称
        'title' => '我的下拉菜单', // 弹出式窗口标题
        'items' => array( // 弹出式窗口中的选项列表
            array('text' => '选项1', 'onclick' => 'alert("选项1")'), // 选项1的功能和点击事件处理函数
            array('text' => '选项2', 'onclick' => 'alert("选项2")') // 选项2的功能和点击事件处理函数
        )
    );
    return $popups;
}

add_filter( 'tiny_mce_before_init', 'advmceconf_config_mce', 1111 );
function advmceconf_config_mce( $config ) {
	global $plugin_page;

	if ( ! empty( $plugin_page ) && $plugin_page == 'advanced-tinymce-configuration' ) {
		global $advmceconf_show_defaults;

		$advmceconf_show_defaults = $config;
		return $config;
	}

	$options = get_option( 'advmceconf_options' );

	if ( empty( $options ) || ! is_array( $options ) ) {
		return $config;
	}

	return array_merge( $config, $options );
}

add_action( 'admin_head-settings_page_advanced-tinymce-configuration', 'advmceconf_style' );
function advmceconf_style() {
	?>
	<style type="text/css">
		.wrap.advmceconf {
			max-width: 80em;
		}

		.advmceconf-wrap {
			border: 1px solid #ddd;
			border-radius: 3px;
			background-color: #f8f8f8;
			padding: .5em 2em 1em;
			margin: 1em 0;
		}

		.advmceconf-wrap img.advmceconf-example {
			border: 1px solid #bbb;
			max-width: 100%;
			height: auto;
		}

		.advmceconf-form {
			padding: 2em 0 0;
		}

		.advmceconf-table {
			table-layout: fixed;
			border-collapse: collapse;
			margin: 0 0 3em;
			width: 100%;
			clear: both;
		}

		.advmceconf-table td {
			padding: 0.3em;
			line-height: 1.5;
			vertical-align: top;
		}

		.advmceconf-table th {
			font-weight: bold;
			text-shadow: rgba(255,255,255,1) 0 1px 0;
			padding: 0.5em 0.5em 0;
			text-align: left;
		}

		.advmceconf-table td.names input {
			width: 100%;
		}

		.advmceconf-table textarea {
			width: 100%;
			min-height: 100px;
			margin: 1px;
		}

		.advmceconf-table th.names {
			width: 24%;
		}

		.advmceconf-table .sep {
			width: 1em;
			text-align: center;
		}

		.advmceconf-table .actions {
			width: 100px;
			text-align: center;
			vertical-align: middle;
		}

		.advmceconf .advmceconf-defaults {
			white-space: -moz-pre-wrap !important;
			word-wrap: break-word;
			white-space: pre-wrap;
		}

		.advmceconf .advmceconf-defaults td,
		.advmceconf .advmceconf-defaults th {
			border-bottom: 1px solid #ddd;
			padding: .6em .3em;
		}

		.advmceconf .advmceconf-defaults th {
			padding-bottom: 0.4em;
		}

		.advmceconf .advmceconf-defaults .names {
			text-align: right;
		}

		.advmceconf .advmceconf-defaults td.actions {
			padding: .3em 0 .4em;
		}

		.advmceconf-code-links a {
			text-decoration: none;
		}

		.advmceconf input[type="text"],
		.advmceconf select,
		.advmceconf textarea,
		.advmceconf .button {
			border-color: #aaa;
		}

		.advmceconf input[type="text"]:focus,
		.advmceconf select:focus,
		.advmceconf textarea:focus,
		.advmceconf .button:focus {
			    border-color: #bbb;
			    box-shadow: 0 0 0 2px #bbb;
		}

		@media screen and (max-width: 782px) {
			.advmceconf-table .actions {
				display: none;
			}
		}
	</style>
	<?php
}

add_action( 'admin_menu', 'advmceconf_menu' );
function advmceconf_menu() {
	if ( function_exists( 'add_options_page' ) ) {
		add_options_page( 'TinyMCE Config', 'TinyMCE Config', 'manage_options', 'advanced-tinymce-configuration', 'advmceconf_admin' );
	}
	// $parent = '';//parent_slug
	// $capability = 'manage_options';
	// add_menu_page( '', 'Menu Item', $capability, $parent, $callback );
	// add_submenu_page( $parent, 'Page Title', 'First Subitem', $capability, $parent, $callback );
	// add_submenu_page( $parent, 'Second Page Title', 'Second Subitem', $capability, 'submenu_slug', $submenu_callback );
}


function advmceconf_admin() {
	global $advmceconf_show_defaults;

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( 'Invalid request' );
	}

	$message = '';
	$options = get_option( 'advmceconf_options', array() );
	$version = get_option( 'advmceconf_version', 0 );

	if ( ! empty( $_POST['advmceconf_save'] ) ) {
		check_admin_referer( 'advmceconf-save-options' );
		$old_options = $options;

		if ( empty( $_POST['advmceconf_options'] ) || ! is_array( $_POST['advmceconf_options'] ) ) {
			$new_options = array();
		} else {
			$new_options = $_POST['advmceconf_options'];
		}

		if ( ! empty( $_POST['advmceconf-new'] ) && isset( $_POST['advmceconf-new-val'] ) ) {
			$new_options[ $_POST['advmceconf-new'] ] = $_POST['advmceconf-new-val'];
		}

		foreach ( $new_options as $key => $val ) {
			$key = preg_replace( '/[^a-z0-9_]+/i', '', $key );
			if ( empty( $key ) )
				continue;

			if ( isset( $_POST[ $key ] ) && empty( $_POST[ $key ] ) ) {
				unset( $options[ $key ] );
				continue;
			}

			$val = trim( stripslashes( $val ) );

			if ( 'true' === $val ) {
				$options[ $key ] = true;
			} elseif ( 'false' === $val ) {
				$options[ $key ] = false;
			} else {
				$options[ $key ] = $val;
			}
		}

		if ( $options != $old_options ) {
			update_option( 'advmceconf_options', $options );
			$message = '<div class="updated fade"><p>' . __( 'Options saved.', 'adv-mce-config' ) . '</p></div>';
		}

		if ( $version < 12 ) {
			update_option( 'advmceconf_version', 12 );
			$version = 12;
		}
	}

	?>
	<div class="wrap advmceconf">
	<h1><?php _e( 'Advanced TinyMCE Settings', 'adv-mce-config' ); ?></h1>
	<?php

	if ( $message ) {
		echo $message;
	}

	$img_src = plugins_url( 'images/', __FILE__ );

	?>
	<div class="advmceconf-wrap">
	<h2><?php _e( '如何：', 'adv-mce-config' ); ?></h2>
	<ol>
		<li><?php _e( '要向 TinyMCE 添加设置，请在左侧键入名称，在右侧键入值。', 'adv-mce-config' ); ?></li>
		<li><?php _e( '不要在名称或值周围添加引号。', 'adv-mce-config' ); ?></li>
		<li><?php _e( '要删除设置，请同时删除 name 和 value。', 'adv-mce-config' ); ?></li>
		<li><?php _e( '要添加布尔值，请键入<code>true</code>或<code>false</code>。保存时，这些字符串将转换布尔值', 'adv-mce-config' ); ?></li>
		<li><?php _e( '您可以在 value 字段中添加 JavaScript 数组、对象和函数。', 'adv-mce-config' ); ?></li>
		<li><?php _e( '从 TinyMCE 文档中的示例复制设置时，请确保仅复制设置名称和值，而不是整个示例。', 'adv-mce-config' ); ?></li>
		<li><?php _e( '粘贴时，请确保 name 和 value 都不以空格开头或结尾。', 'adv-mce-config' ); ?></li>
		<li><?php _e( 'name 和 value 都必须遵循 JavaScript 语法。仅当使用数组或对象时，才允许换行。', 'adv-mce-config' ); ?></li>
	</ol>

	<h3><?php _e( '例：', 'adv-mce-config' ); ?></h3>
	<p><?php _e( '要从 TinyMCE 文档中的示例中添加<code>block_formats</code>设置,请执行以下作：', 'adv-mce-config' ); ?></p>
	<p>
		<pre class="highlightjs highlight">
			<code class="language-js hljs" data-lang="js">
			tinymce.init(
				{
				selector: 'textarea'  // change this value according to your HTML
				height: 300
				min_height: 200
				width: 300
				min_width: 400
				max_width: 500
				resize: false //true, false, 'both'

				skin: 'oxide'
				content_css: 'fabric'  // Name of the content skin
				skin_url: '/css/mytinymceskin'

				theme: 'silver'
				theme_url: '/mytheme/mytheme.js'

				icons_url: 'https://www.example.com/icons/material/icons.js', // load icon pack
				icons: 'material'  // use icon pack

				toolbar_mode: 'floating'
				toolbar_mode: 'sliding'
				toolbar_mode: 'scrolling'
				toolbar_mode: 'wrap'
				toolbar_location: 'bottom'
				toolbar_sticky: true
				toolbar_sticky_offset: 100
				toolbar_persist: true
				fixed_toolbar_container: '#mytoolbar'
				toolbar: 'undo redo | styles | bold italic | link image'
				toolbar: 'undo redo styles bold italic alignleft aligncenter alignright alignjustify | bullist numlist outdent indent'
				toolbar: [
				    'undo redo | styles | bold italic | link image',
				    'alignleft aligncenter alignright'
				]

				toolbar: [
				    { name: 'history', items: [ 'undo', 'redo' ] },
				    { name: 'styles', items: [ 'styles' ] },
				    { name: 'formatting', items: [ 'bold', 'italic' ] },
				    { name: 'alignment', items: [ 'alignleft', 'aligncenter', 'alignright', 'alignjustify' ] },
				    { name: 'indentation', items: [ 'outdent', 'indent' ] }
				]
				toolbar: 'formatting | alignleft aligncenter alignright',
				toolbar_groups: {
					formatting: {
					  icon: 'bold',
					  tooltip: 'Formatting',
					  items: 'bold italic underline | superscript subscript'
					}
				}
				toolbar1: 'undo redo | styles | bold italic | link image',
  				toolbar2: 'alignleft aligncenter alignright'
				toolbar_location: 'bottom'
				toolbar_sticky: true
				toolbar_sticky: true,
				toolbar_sticky_offset: 100
				menubar: 'file edit insert view format table tools help'
				removed_menuitems: 'undo redo'
				menu: {
					file: { title: 'File', items: 'newdocument restoredraft | preview | importword exportpdf exportword | print | deleteallconversations' },
					edit: { title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall | searchreplace' },
					view: { title: 'View', items: 'code revisionhistory | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments' },
					insert: { title: 'Insert', items: 'image link media addcomment pageembed codesample inserttable | math | charmap emoticons hr | pagebreak nonbreaking anchor tableofcontents | insertdatetime' },
					format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript codeformat | styles blocks fontfamily fontsize align lineheight | forecolor backcolor | language | removeformat' },
					tools: { title: 'Tools', items: 'spellchecker spellcheckerlanguage | a11ycheck code wordcount' },
					table: { title: 'Table', items: 'inserttable | cell row column | advtablesort | tableprops deletetable' },
					help: { title: 'Help', items: 'help' }
				}

				inline: true
				inline: true,
				toolbar_persist: true
				fixed_toolbar_container: '#mytoolbar'
				fixed_toolbar_container_target: el

				target: el
				placeholder: 'Type here...'
				auto_focus: 'element1'
				custom_ui_selector: '.my-custom-button'
				highlight_on_focus: false
				plugins: 'advlist autolink link image lists charmap preview' //using plugins with a string
				plugins: [ 'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview' ] //using plugins with an array
				plugins: 'link image table',
				plugins: 'quickbars',
				quickbars_selection_toolbar: 'bold italic | blocks | quicklink blockquote'
				quickbars_insert_toolbar: 'quickimage quicktable | hr pagebreak'
				quickbars_image_toolbar: 'alignleft aligncenter alignright | rotateleft rotateright | imageoptions'
				editimage_toolbar: 'rotateleft rotateright | flipv fliph | editimage imageoptions'
				table_toolbar: 'tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol'


  				contextmenu: 'link image table'
  				contextmenu_avoid_overlap: '.mce-spelling-word'
  				contextmenu_never_use_native: true
				external_plugins: {
					'testing': 'http://www.testing.com/plugin.min.js',
					'maths': 'http://www.maths.com/plugin.min.js'
				}
				readonly: true
				content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:16px }'
				disabled: true
				setup: (editor) => {
				editor.on('click', () => {
				  console.log('Editor was clicked');
				});
				}
				init_instance_callback: (editor) => {
				console.log(`Editor: ${editor.id} is now initialized.`);
				}
				base_url: '/my/tinymce/dir'
				cache_suffix: '?v=4.1.6'
				suffix: '.min'
				content_security_policy: "default-src 'self'"
				referrer_policy: 'origin'
				promotion: true


				}
			);
			</code>
		</pre>
	</p>
	<p><?php _e( '您需要在 Option name 字段和 Value 字段中输入：<code>block_formats</code><code>Paragraph=p;Header 1=h1;Header 2=h2;Header 3=h3</code>', 'adv-mce-config' ); ?></p>
	<p>
		<table class="advmceconf-table advmceconf-set">
			<thead>
				<tr>
					<th class="names"><?php _e( 'Option name', 'adv-mce-config' ); ?></th>
					<th class="values"><?php _e( 'Value', 'adv-mce-config' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<tr id="advmceconf-new-row">
					<td class="names">
						<input type="text" name="advmceconf-new" id="advmceconf-new" value="block_formats">
					</td>
					<td class="values">
						<textarea name="advmceconf-new-val" id="advmceconf-new-val" value="Paragraph=p;Header 1=h1;Header 2=h2;Header 3=h3"></textarea>
					</td>
				</tr>
			</tbody>
		</table>
	</p>

	<p>
		<a href="https://www.tiny.cloud/docs-4x/" target="_blank" rel="noreferrer noopener">
			<?php _e( 'TinyMCE 文档', 'adv-mce-config' ); ?>
		</a><?php _e( '提供了所有设置的说明。', 'adv-mce-config' ); ?>.
	</p>
	<p><?php _e( '一些更常用的设置：', 'adv-mce-config' ); ?></p>
	<ul class="ul-disc advmceconf-code-links">
		<li><a href="https://www.tiny.cloud/get-tiny/self-hosted/" target="_blank" rel="noreferrer noopener">免费版下载</a></li>
		<li><a href="http://tinymce.ax-z.cn/" target="_blank" rel="noreferrer noopener">中文文档</a></li>
	</ul>
	</div>

	<h2><?php _e( '默认', 'adv-mce-config' ); ?></h2>
	<div class="showhide" style="display: none;">
	<?php

	ob_start();
	wp_editor( '', 'content', array( 'media_buttons' => false, 'quicktags' => false ) );
	ob_end_clean();

	$edit   = esc_html( _x( 'Edit', 'Edit options button', 'adv-mce-config' ) );
	$change = esc_html( __( 'Change', 'adv-mce-config' ) );

	if ( ! empty( $advmceconf_show_defaults ) && is_array( $advmceconf_show_defaults ) ) {
		?>
		<table class="advmceconf-table advmceconf-defaults advmceconf-initial">
		<thead>
			<tr>
				<th class="names"><?php _e( 'Name', 'adv-mce-config' ); ?></th>
				<th class="sep">:</th>
				<th><?php _e( 'Default value', 'adv-mce-config' ); ?></th>
				<th class="actions">&nbsp;</th>
			</tr>
		</thead>
		<tbody>
		<?php

		foreach ( $advmceconf_show_defaults as $def_field => $def_value ) {
			if ( is_bool( $def_value ) ) {
				$def_value = $def_value ? 'true' : 'false';
			}

			if ( array_key_exists( $def_field, $options ) ) {
				$tr_class = ' class="highlight"';
				$edit_class = ' changed';
				$button = $edit;
			} else {
				$tr_class = '';
				$edit_class = '';
				$button = $change;
			}

			?>
			<tr<?php echo $tr_class; ?>>
				<td class="names"><?php echo $def_field; ?></td>
				<td class="sep">:</td>
				<td class="values"><?php echo htmlspecialchars( $def_value, ENT_QUOTES ); ?></td>
				<td class="actions"><button type="button" class="button<?php echo $edit_class; ?>" data-optname="<?php echo esc_attr( $def_field ); ?>"><?php echo $button; ?></button></td>
			</tr>
			<?php

		}

		?>
		</tbody>
		</table>
		<?php

		if ( ! empty( $options ) ) {
			$added_options   = array_diff_key( $options, $advmceconf_show_defaults );
			$changed_options = array_intersect_key( $options, $advmceconf_show_defaults );


			if ( ! empty( $added_options ) ) {
				?>
				<h3><?php _e( 'Options added with this plugin', 'adv-mce-config' ) ?></h3>
				<table class="advmceconf-table advmceconf-defaults advmceconf-added">
				<thead>
					<tr>
						<th class="names"><?php _e( 'Name', 'adv-mce-config' ); ?></th>
						<th class="sep">:</th>
						<th><?php _e( 'Value', 'adv-mce-config' ); ?></th>
						<th class="actions">&nbsp;</th>
					</tr>
				</thead>
				<tbody>
				<?php

				foreach ( $added_options as $opt_field => $opt_value ) {
					if ( is_bool( $opt_value ) ) {
						$opt_value = $opt_value ? 'true' : 'false';
					}

					?>
					<tr>
						<td class="names"><?php echo $opt_field; ?></td>
						<td class="sep">:</td>
						<td><?php echo htmlspecialchars( $opt_value, ENT_QUOTES ); ?></td>
						<td class="actions"><button type="button" class="button current-option" data-optname="<?php echo esc_attr( $opt_field ); ?>"><?php echo $edit; ?></button></td>
					</tr>
					<?php
				}

				?>
				</tbody>
				</table>
				<?php
			}

			if ( ! empty( $changed_options ) ) {
				?>
				<h3><?php _e( 'Options changed from this plugin', 'adv-mce-config' ) ?></h3>
				<table class="advmceconf-table advmceconf-defaults advmceconf-changed">
				<thead>
					<tr>
						<th class="names"><?php _e( 'Name', 'adv-mce-config' ); ?></th>
						<th class="sep">:</th>
						<th><?php _e( 'Value', 'adv-mce-config' ); ?></th>
						<th class="actions">&nbsp;</th>
					</tr>
				</thead>
				<tbody>
				<?php

				$edit = esc_attr( _x( 'Edit', 'Edit options button', 'adv-mce-config' ) );

				foreach ( $changed_options as $opt_field => $opt_value ) {
					if ( is_bool( $opt_value ) ) {
						$opt_value = $opt_value ? 'true' : 'false';
					}

					?>
					<tr>
						<td class="names"><?php echo $opt_field; ?></td>
						<td class="sep">:</td>
						<td><?php echo htmlspecialchars( $opt_value, ENT_QUOTES ); ?></td>
						<td class="actions"><button type="button" class="button current-option" data-optname="<?php echo esc_attr( $opt_field ); ?>"><?php echo $edit; ?></button></td>
					</tr>
					<?php
				}

				?>
				</tbody>
				</table>
				<?php
			}
		}
	}

	?>
	</div>

	<p>
		<button type="button" class="button showhide"><?php _e( '显示 TinyMCE 默认设置', 'adv-mce-config' ); ?></button>
		<button type="button" class="button showhide" style="display: none;"><?php _e( '关闭 TinyMCE 默认设置', 'adv-mce-config' ); ?></button>
	</p>

	<form method="post" action="" class="advmceconf-form">
	<h2><?php _e( '编辑设置', 'adv-mce-config' ); ?></h2>
	<table class="advmceconf-table advmceconf-set">
	<?php

	if ( empty( $options ) ) {
		?>
		<tr><td><?php _e( '尚未添加任何选项。添加新选项后，它将在此处可供编辑。', 'adv-mce-config' ); ?></td></tr>
		<?php
	} else {
		$remove = esc_attr( __( '清除', 'adv-mce-config' ) );

		?>
		<thead>
			<tr>
				<th class="names"><?php _e( 'Name', 'adv-mce-config' ); ?></th>
				<th class="values"><?php _e( 'Value', 'adv-mce-config' ); ?></th>
				<th class="actions">&nbsp;</th>
			</tr>
		</thead>
		<tbody>
		<?php

		foreach ( $options as $field => $value ) {
			$field = esc_attr( $field );
			$id = "advmceconf_option-{$field}";
			$name = "advmceconf_options[{$field}]";

			if ( is_bool( $value ) ) {
				$value = $value ? 'true' : 'false';
			}

			?>
			<tr>
				<td class="names">
					<input type="text" name="<?php echo $field; ?>" id="<?php echo $field; ?>" value="<?php echo $field; ?>" spellcheck="false">
				</td>
				<td class="values">
					<textarea name="<?php echo $name; ?>" id="<?php echo $id; ?>" spellcheck="false"><?php echo htmlspecialchars( $value, ENT_NOQUOTES ); ?></textarea>
				</td>
				<td class="actions">
					<button type="button" class="button remove"><?php echo $remove; ?></button>
				</td>
			</tr>
			<?php
		}
	}

	?>
	</tbody>
	</table>

	<h2><?php _e( '添加选项', 'adv-mce-config' ); ?></h2>
	<table class="advmceconf-table advmceconf-set">
	<thead>
		<tr>
			<th class="names"><?php _e( 'Name', 'adv-mce-config' ); ?></th>
			<th class="values"><?php _e( 'Value', 'adv-mce-config' ); ?></th>
			<th class="actions">&nbsp;</th>
		</tr>
	</thead>
	<tbody>
		<tr id="advmceconf-new-row">
			<td class="names">
				<input type="text" name="advmceconf-new" id="advmceconf-new" value="" spellcheck="false">
			</td>
			<td class="values">
				<textarea name="advmceconf-new-val" id="advmceconf-new-val" spellcheck="false"></textarea>
			</td>
			<td class="actions">&nbsp;</td>
		</tr>
	</tbody>
	</table>


	<p class="submit">
		<?php wp_nonce_field( 'advmceconf-save-options' ); ?>
		<input type="submit" value="<?php esc_attr_e( 'Save Changes', 'adv-mce-config' ); ?>" class="button-primary" name="advmceconf_save" />
	</p>
	</form>
	</div>

	<script type="text/javascript">
	jQuery( document ).ready( function( $ ) {

		function scrollToRow( row ) {
			$( '.advmceconf-set tr' ).removeClass( 'highlight' );

			if ( row.length ) {
				row.addClass( 'highlight' );
				row[0].scrollIntoView( {
					behavior: 'smooth',
					block: 'center',
				} );
			}
		}

		$( 'button.showhide' ).on( 'click', function() {
			$( 'div.showhide, button.showhide' ).toggle();
		});


		$( '.advmceconf-initial button' ).on( 'click', function( event ) {
			var target     = $( event.target );
			var optionName = target.data( 'optname' );
			var row;

			if ( target.hasClass( 'changed' ) ) {
				scrollToRow( $( '#' + optionName ).closest( 'tr' ) );
			} else {
				row = target.closest( 'tr' );
				$( '#advmceconf-new' ).val( row.find( 'td.names' ).text() );
				$( '#advmceconf-new-val' ).val( row.find( 'td.values' ).text() );

				scrollToRow( $( '#advmceconf-new-row' ) );
			}
		});


		$( '.advmceconf-added button, .advmceconf-changed button' ).on( 'click', function( event ) {
			var optionName = $( event.target ).data( 'optname' );

			scrollToRow( $( '#' + optionName ).closest( 'tr' ) );
		});

		$( '.advmceconf-set button' ).on( 'click', function( event ) {
			var target = $( event.target );

			if ( target.hasClass( 'remove' ) ) {
				target.closest( 'tr' ).find( 'input[type="text"], textarea' ).val( '' );
			}
		});
	});
	</script>
	<?php
}


add_action( 'admin_menu', 'tinymce_menu' );
function tinymce_menu() {
	if ( function_exists( 'add_options_page' ) ) {
		add_options_page( 'TinyMCE', 'TinyMCE', 'manage_options', 'tinymce', 'tinymce' );
	}
}


function tinymce() {

?>

<div class="wrap advmceconf">
	<h2 class="pagetitle" _msttexthash="13870324" _msthash="45">快速标记 API</h2>
<p>JavaScript API提供了一种简单的方法来添加自定义按钮并将代码和内容注入编辑器文本区域。该QTags.addButton方法增加一个按钮，工具栏和定义如下：</p>
<pre>
QTags.addButton( 
	id, 
	display, 
	arg1, 
	arg2, 
	access_key, 
	title, 
	priority, 
	instance 
);
</pre>
<h2><span class="mw-headline" id="Usage" _msttexthash="5626816" _msthash="62">用法</span></h2>
<pre>QTags.addButton( id, display, arg1, arg2, access_key, title, priority, instance );</pre>
<p>此方法保留以下参数：</p>
<ul>
<li><strong>id</strong>&nbsp;(&nbsp;<em>string</em> ) (required) 是按钮的HTML id；</li>
<li><strong>display</strong>&nbsp;(&nbsp;<em>string</em> ) (required) 是HTML值；</li>
<li><strong>arg1</strong>&nbsp;(&nbsp;<em>string</em>&nbsp;) (必需) 是要包含的开始标记或单击按钮时要运行的自定义回调函数；</li>
<li><strong>arg2</strong>&nbsp;(&nbsp;<em>string</em>&nbsp;) (可选) 是结束标签；</li>
<li><strong>access_key</strong>&nbsp;(&nbsp;<em>string</em>&nbsp;) (可选) 是按钮的快捷键；</li>
<li><strong>title</strong>&nbsp;(&nbsp;<em>string</em> ) (可选) 是HTML标题；</li>
<li><strong>优先级</strong>（<em>int</em>）（可选）是一个数字，表示按钮在工具栏中的位置；</li>
<li><strong>实例</strong>（<em>字符串</em>）（可选）将按钮限制为特定的Quicktags实例。</li>
</ul>
<h2><span class="mw-headline" id="Examples" _msttexthash="4284137" _msthash="91">例子</span></h2>
<pre>
// add more buttons to the html editor
function appthemes_add_quicktags() {
    if (wp_script_is('quicktags')){
?&gt;
    &lt;script type="text/javascript"&gt;
    QTags.addButton( 'eg_paragraph', 'p', '&lt;p&gt;', '&lt;/p&gt;', 'p', 'Paragraph tag', 1 );
    QTags.addButton( 'eg_hr', 'hr', '&lt;hr /&gt;', '', 'h', 'Horizontal rule line', 201 );
    QTags.addButton( 'eg_pre', 'pre', '&lt;pre lang="php"&gt;', '&lt;/pre&gt;', 'q', 'Preformatted text tag', 111 );
    &lt;/script&gt;
&lt;?php
    }
}
add_action( 'admin_print_footer_scripts', 'appthemes_add_quicktags' );
</pre>
<pre>
add_action( 'admin_enqueue_scripts', 'enqueue_quicktag_script' )
function enqueue_quicktag_script(){
  wp_enqueue_script( 'your-handle', plugin_dir_url( __FILE__ ) . 'path/to/script.js', array( 'jquery', 'quicktags' ), '1.0.0', true );
}
</pre>
<p><strong _msttexthash="7853560" _msthash="98">JS 本身</strong></p>
<pre>
QTags.addButton( 
    'my_quicktag_id', 
    'My Quicktag Label', 
    my_callback
);
function my_callback(){
  // do anything on click and after here
  //console.log('it was clicked')
  var my_stuff = prompt( 'Enter Some Stuff:', '' );
     
  if ( my_stuff ) {
    QTags.insertContent('&lt;p&gt;' + my_stuff + '&lt;/p&gt;');
  }
}
</pre>
<h2><span class="mw-headline" id="Default_Quicktags">默认情况下，WordPress提供以下快速标签：</span></h2>
<p>以下是 WordPress 添加到文本编辑器的默认 Quicktag 的值（按访问键值排序的表）。Access Key 和 ID 必须唯一。由于Quicktags API，可以覆盖默认设置。</p>
<table class="widefat">
<tbody><tr style="background:#464646; color:#d7d7d7;">
<th> <b>Accesskey</b> </th>
<th> <b>ID</b> </th>
<th> <b>Value</b> </th>
<th> <b>Tag Start</b> </th>
<th> <b>Tag End</b>
</th></tr>
<tr>
<td> a </td>
<td> link </td>
<td> link </td>
<td> <tt>&lt;a href="' + URL + '"&gt;</tt> </td>
<td> <tt>&lt;/a&gt;</tt>
</td></tr>
<tr>
<td> b </td>
<td> strong </td>
<td> b </td>
<td> <tt>&lt;strong&gt;</tt> </td>
<td> <tt>&lt;/strong&gt;</tt>
</td></tr>
<tr>
<td> c </td>
<td> code </td>
<td> code </td>
<td> <tt>&lt;code&gt;</tt> </td>
<td> <tt>&lt;/code&gt;</tt>
</td></tr>
<tr>
<td> d </td>
<td> del </td>
<td> del </td>
<td> <tt>&lt;del datetime="' + _datetime + '"&gt;</tt> </td>
<td> <tt>&lt;/del&gt;</tt>
</td></tr>
<tr>
<td> f </td>
<td> fullscreen </td>
<td> fullscreen </td>
<td>  </td>
<td>
</td></tr>
<tr>
<td> i </td>
<td> em </td>
<td> i </td>
<td> <tt>&lt;em&gt;</tt> </td>
<td> <tt>&lt;/em&gt;</tt>
</td></tr>
<tr>
<td> l </td>
<td> li </td>
<td> li </td>
<td> <tt>\t&lt;li&gt;</tt> </td>
<td> <tt>&lt;/li&gt;\n</tt>
</td></tr>
<tr>
<td> m </td>
<td> img </td>
<td> img </td>
<td> <tt>&lt;img src="' + src + '" alt="' + alt + '" /&gt;</tt> </td>
<td>
</td></tr>
<tr>
<td> o </td>
<td> ol </td>
<td> ol </td>
<td> <tt>&lt;ol&gt;\n</tt> </td>
<td> <tt>&lt;/ol&gt;\n\n</tt>
</td></tr>
<tr>
<td> q </td>
<td> block </td>
<td> b-quote </td>
<td> <tt>\n\n&lt;blockquote&gt;</tt> </td>
<td> <tt>&lt;/blockquote&gt;\n\n</tt>
</td></tr>
<tr>
<td> s </td>
<td> ins </td>
<td> ins </td>
<td> <tt>&lt;ins datetime="' + _datetime + '"&gt;</tt> </td>
<td> <tt>&lt;/ins&gt;</tt>
</td></tr>
<tr>
<td> t </td>
<td> more </td>
<td> more </td>
<td> <tt>&lt;!--more--&gt;</tt> </td>
<td>
</td></tr>
<tr>
<td> u </td>
<td> ul </td>
<td> ul </td>
<td> <tt>&lt;ul&gt;\n</tt> </td>
<td> <tt>&lt;/ul&gt;\n\n</tt>
</td></tr>
<tr>
<td>  </td>
<td> spell </td>
<td> lookup </td>
<td>  </td>
<td>
</td></tr>
<tr>
<td>  </td>
<td> close </td>
<td> close </td>
<td>  </td>
<td>
</td></tr></tbody></table>


	<?php 
		$settings = array(
			'theme'                        => 'modern',
			'skin'                         => 'lightgray',
			'language'                     => '',
			'formats'                      => '{' .
				'alignleft: [' .
					'{selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li", styles: {textAlign:"left"}},' .
					'{selector: "img,table,dl.wp-caption", classes: "alignleft"}' .
				'],' .
				'aligncenter: [' .
					'{selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li", styles: {textAlign:"center"}},' .
					'{selector: "img,table,dl.wp-caption", classes: "aligncenter"}' .
				'],' .
				'alignright: [' .
					'{selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li", styles: {textAlign:"right"}},' .
					'{selector: "img,table,dl.wp-caption", classes: "alignright"}' .
				'],' .
				'strikethrough: {inline: "del"}' .
			'}',
			'relative_urls'                => false,
			'remove_script_host'           => false,
			'convert_urls'                 => false,
			'browser_spellcheck'           => true,
			'fix_list_elements'            => true,
			'entities'                     => '38,amp,60,lt,62,gt',
			'entity_encoding'              => 'raw',
			'keep_styles'                  => false,
			'cache_suffix'                 => 'wp-mce-',
			'resize'                       => 'vertical',
			'menubar'                      => false,
			'branding'                     => false,

			// Limit the preview styles in the menu/toolbar.
			'preview_styles'               => 'font-family font-size font-weight font-style text-decoration text-transform',

			'end_container_on_empty_block' => true,
			'wpeditimage_html5_captions'   => true,
			'wp_lang_attr'                 => get_bloginfo( 'language' ),
			'wp_shortcut_labels'           => '',//wp_json_encode(),
		);
		$plugins = array(
					'charmap',
					'colorpicker',
					'hr',
					'lists',
					'paste',
					'tabfocus',
					'textcolor',
					'fullscreen',
					'wordpress',
					'wpautoresize',
					'wpeditimage',
					'wpemoji',
					'wpgallery',
					'wplink',
					'wptextpattern',
					//'wpview','wpdialogs','media'//wp-before-tinymce-init
				);
		wp_enqueue_script( 'editor' );
		wp_enqueue_script( 'quicktags' );
		wp_enqueue_style( 'buttons' );
		wp_enqueue_script( 'wplink' );
		wp_enqueue_script( 'jquery-ui-autocomplete' );
		add_thickbox();
		wp_enqueue_script( 'media-upload' );
		wp_enqueue_script( 'wp-embed' );
		wp_editor(
			'精简模式', //$content,
			'myeditor', //$editor_id
			array(//$settings
		        'wpautop'             => ! has_blocks(),
				'media_buttons'       => true,
				'default_editor'      => '',
				'drag_drop_upload'    => false,
				'textarea_name'       => '',
				'textarea_rows'       => get_option('default_post_edit_rows', 10), //Determine the number of rows.
				'tabindex'            => '',
				'tabfocus_elements'   => ':prev,:next',
				'editor_css'          => '',
				'editor_class'        => '',
				'teeny'               => false,//只加载基本插件包括inlinepopups、fullscreen、wordpress、wplink和wpdialogs，全屏插件是wpfullscreen
				'_content_editor_dfw' => false,
		        'tinymce' => array(
		        	//'teeny_mce_plugins' => 'colorpicker,lists,fullscreen,image,wordpress,wpeditimage,wplink',
		        	'plugins' => 'charmap,colorpicker,hr,lists,media,paste,tabfocus,textcolor,fullscreen,wordpress,wpautoresize,wpeditimage,wpemoji,wpgallery,wplink,wpdialogs,wptextpattern,wpview',
		        	//'skin' => 'default',//可选的皮肤：default、wp_theme、o2k7和highcontrast
		        	// 'theme_advanced_buttons1' => 'undo,redo,|,bold,italic,underline,strikethrough|,justifyleft,justifycenter,justifyright,justifyfull,|,forecolor,backcolor',
                    // 'theme_advanced_buttons2' => 'cut,copy,paste,|,bullist,numlist,blockquote,|,link,unlink,anchor,image,|,sub,sup,hr',
                    // 'toolbar1'      => 'bold,italic,underline,separator,alignleft,aligncenter,alignright,separator,link,unlink,undo,redo',
			        // 'toolbar2'      => '',
			        // 'toolbar3'      => '',
			        'selector'          => '',
					'wpautop'           => '',
					'indent'            => '',
					// 'toolbar1'          => implode( ',', $mce_buttons ),
					// 'toolbar2'          => implode( ',', $mce_buttons_2 ),
					// 'toolbar3'          => implode( ',', $mce_buttons_3 ),
					// 'toolbar4'          => implode( ',', $mce_buttons_4 ),
					'tabfocus_elements' => '',
					'body_class'        => '',
		        ),
		        'quicktags' => array(
		        	//'teeny_buttons' => 'bold,italic,underline,blockquote,strikethrough,bullist,numlist,alignleft,aligncenter,alignright,undo,redo,link,fullscreen,'
		        	//'mce_buttons' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,wp_more,spellchecker,'
		        	//'mce_buttons_2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,'
		        	//'buttons'      => 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close,dfw',
		        	'buttons' => 'strong,em,link,ul,ol,li,code',
		        ),
		    )
	    );
	}
	?>
</div>